<?php
declare (strict_types=1);

namespace app\advertiser\service;

use app\admin\model\advertiser\AdvertiserUser;
use app\admin\service\base\JwtService;
use app\advertiser\validates\AdvertiserUserValidate;
use app\BaseService;
use ciphertext\RsaPassword;
use ciphertext\TpSms;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 广告主用户服务层
 */
class AdvertiserUserService extends BaseService
{

    /**
     * 广告主注册
     * @param array $params
     * @return Json
     */
    public function adUserAdd(array $params): Json
    {
        //先解密密码
        $params['password'] = RsaPassword::privateDecrypt($params['password']);
        //数据验证
        try {
            validate(AdvertiserUserValidate::class)->scene('register')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        //判断手机号是否重复
        $res = AdvertiserUser::findOne(['phone' => $params['phone']]);
        if ($res) {
            return jsonReturn(0, [], '手机号已存在');
        }
        //验证手机验证码
        $tpSms = new TpSms();
        $res = $tpSms->mobile($params['phone'])->code($params['code'])->scene('adUserCode')->check();
        if (!$res) {
            //验证失败，获取失败信息
            return jsonReturn(0, [], $tpSms->getErrorMsg());
        }
        //处理参数
        $params['safe_code'] = substr(md5(uniqid()), 5, 10);
        $value = $params['password'] . $params['safe_code'];
        $params['password'] = password_hash($value, PASSWORD_DEFAULT);
        $params['enable'] = 1;
        $params['closed'] = 0;
        $params['create_time'] = time();
        $params['update_time'] = time();
        //保存至数据库
        $user_id = AdvertiserUser::strict(false)->insertGetId($params);
        if ($user_id) {
            return jsonReturn(1, [], '注册成功');
        }
        return jsonReturn(0, [], '注册失败');
    }

    /**
     * 获取验证码
     * @param array $params
     * @return Json
     */
    public function adUserCode(array $params): Json
    {
        //数据验证
        try {
            validate(AdvertiserUserValidate::class)->scene('getCode')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        //发送验证码
        $code = (new TpSms())->mobile($params['phone'])->scene('adUserCode')->create();
        return jsonReturn(1, ['code' => $code], '获取成功');
    }

    /**
     * 广告主登录
     * @param array $params
     * @return Json
     */
    public function adUserLogin(array $params): Json
    {
        //先解密密码
        $params['password'] = RsaPassword::privateDecrypt($params['password']);
        //数据验证
        try {
            validate(AdvertiserUserValidate::class)->scene('login')->check($params);
        } catch (ValidateException $e) {
            //验证失败输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        //执行登录
        $where = ['phone' => $params['phone'], 'closed' => 0, 'enable' => 1];
        $user = AdvertiserUser::where($where)->find();
        if (!$user) {
            return jsonReturn(0, [], '账号不存在');
        }
        //验证账号密码
        if (!password_verify($params['password'] . $user->safe_code, $user->password)) {
            return jsonReturn(0, ['err' => '密码不正确'], '密码不正确');
        }
        //更新数据库
        $user->save(['login_ip' => request()->ip(), 'login_time' => time()]);
        //登录程序
        $jst_data = JwtService::authorizations('advertiser', intval($user->id));
        if (!$jst_data['bool']) {
            return jsonReturn(0, [], '签发token失败');
        }
        return jsonReturn(1, [], '登录成功');
    }

    /**
     * 广告主找回密码
     * @param array $params
     * @return Json
     */
    public function adUserPwd(array $params): Json
    {
        //先解密密码
        $params['password'] = RsaPassword::privateDecrypt($params['password']);
        //数据验证
        try {
            validate(AdvertiserUserValidate::class)->scene('adUserPwd')->check($params);
        } catch (ValidateException $e) {
            //验证失败输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        //验证手机验证码
        $tpSms = new TpSms();
        $res = $tpSms->mobile($params['phone'])->code($params['code'])->scene('adUserCode')->check();
        if (!$res) {
            //验证失败，获取失败信息
            return jsonReturn(0, [], $tpSms->getErrorMsg());
        }
        //验证通过执行重置密码
        $where = ['phone' => $params['phone'], 'closed' => 0, 'enable' => 1];
        $user = AdvertiserUser::where($where)->find();
        if (!$user) {
            return jsonReturn(0, [], '账号不存在');
        }
        //处理参数
        $temps['safe_code'] = substr(md5(uniqid()), 5, 10);
        $value = $params['password'] . $temps['safe_code'];
        $temps['password'] = password_hash($value, PASSWORD_DEFAULT);
        //更新密码至数据库
        $res = $user->save($temps);
        if ($res) {
            return jsonReturn(1, [], '找回成功');
        }
        return jsonReturn(0, [], '找回失败');
    }

    /**
     * 广告主找回密码
     * @param array $params
     * @return Json
     */
    public function adUserEditPwd(array $params): Json
    {
        //先解密密码
        $old_password = RsaPassword::privateDecrypt($params['old_password']);
        $new_password = RsaPassword::privateDecrypt($params['new_password']);
        //数据验证
        try {
            validate(AdvertiserUserValidate::class)->scene('adUserPwd')->check(['password' => $new_password]);
        } catch (ValidateException $e) {
            //验证失败输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        //获取当前用户对象
        $where = ['id' => WS_AD_USER_ID];
        $user = AdvertiserUser::where($where)->find();
        if (!$user) {
            return jsonReturn(0, [], '账号不存在');
        }
        //验证旧密码
        if (!password_verify($old_password . $user->safe_code, $user->password)) {
            return jsonReturn(0, ['err' => '密码不正确'], '密码不正确');
        }
        //设置新密码
        $temps['safe_code'] = substr(md5(uniqid()), 5, 10);
        $value = $new_password . $temps['safe_code'];
        $temps['password'] = password_hash($value, PASSWORD_DEFAULT);
        //更新密码至数据库
        $res = $user->save($temps);
        if ($res) {
            return jsonReturn(1, [], '修改成功');
        }
        return jsonReturn(0, [], '修改失败');
    }


}
